from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
from django.db.models import Q

from .models import CourseOrg, CityDict, Teacher
from operation.models import UserFavorite
from courses.models import Course
from .forms import AnotherUserForm

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger


# Create your views here.

class OrgView(View):
    def get(self, request):
        all_orgs = CourseOrg.objects.all()
        all_citys = CityDict.objects.all()
        hot_orgs = all_orgs.order_by('-click_nums')[:3]

        # 搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_orgs = all_orgs.filter(Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords))

        # 筛选城市
        try:
            city_id = request.GET.get('city', '')
        except Exception:
            city_id = None
        if city_id:
            all_orgs = all_orgs.filter(city_id=int(city_id))

        # 筛选城市
        try:
            category = request.GET.get('ct', '')
        except Exception:
            category = None
        if category:
            all_orgs = all_orgs.filter(category=category)

        # 排行
        try:
            sort = request.GET.get('sort', '')
        except Exception:
            sort = None
        if sort == 'students':
            all_orgs = all_orgs.order_by('-students')
        elif sort == 'courses':
            all_orgs = all_orgs.order_by('-course_nums')

        org_nums = all_orgs.count()

        # 对课程机构进行分类
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        # Provide Paginator with the request object for complete querystring generation
        p = Paginator(all_orgs, request=request, per_page=3)

        orgs = p.page(page)

        return render(request, 'org-list.html', {
            "all_orgs": orgs,
            'all_citys': all_citys,
            'org_nums': org_nums,
            'city_id': city_id,
            'category': category,
            'hot_orgs': hot_orgs,
            'sort': sort,
        })


class AddUserAskView(View):
    def post(self, request):
        userask_form = AnotherUserForm(request.GET)
        if userask_form.is_valid():
            user_ask = userask_form.save(commit=True)
            status = "success"
        else:
            status = 'fail'
        msg = '添加出错'
        res = {'status': status, 'msg': msg}
        return JsonResponse(res)


class OrgHomeView(View):
    def get(self, request, org_id):
        course_org = CourseOrg.objects.filter(id=org_id).first()
        course_org.click_nums += 1
        course_org.save()
        current_page = 'home'
        has_fav = False
        if request.user:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2).first():
                has_fav = True
        all_course = course_org.course_set.all()[:3]
        all_teachers = course_org.teacher_set.all()[:1]
        return render(request, 'org-detail-homepage.html', {
            "all_course": all_course,
            "all_teachers": all_teachers,
            "course_org": course_org,
            "current_page": current_page,
            'has_fav': has_fav
        })


class OrgCourseView(View):
    def get(self, request, org_id):
        current_page = 'course'
        course_org = CourseOrg.objects.filter(id=org_id).first()
        has_fav = False
        if request.user:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2).first():
                has_fav = True
        all_course = course_org.course_set.all()
        return render(request, 'org-detail-course.html', {
            "all_course": all_course,
            "course_org": course_org,
            "current_page": current_page,
            'has_fav': has_fav
        })


class OrgDescView(View):
    def get(self, request, org_id):
        current_page = 'desc'
        course_org = CourseOrg.objects.filter(id=org_id).first()
        has_fav = False
        if request.user:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2).first():
                has_fav = True
        return render(request, 'org-detail-desc.html', {
            "course_org": course_org,
            "current_page": current_page,
            'has_fav': has_fav
        })


class OrgTeacherView(View):
    def get(self, request, org_id):
        current_page = 'teacher'
        course_org = CourseOrg.objects.filter(id=org_id).first()
        all_teachers = course_org.teacher_set.all()
        has_fav = False
        if request.user:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2).first():
                has_fav = True
        return render(request, 'org-detail-teachers.html', {
            "course_org": course_org,
            "all_teachers": all_teachers,
            "current_page": current_page,
            'has_fav': has_fav
        })


class AddfavView(View):
    def post(self, request):
        fav_id = request.POST.get('fav_id', 0)
        fav_type = request.POST.get('fav_type', 0)
        if not request.user:
            return JsonResponse({'status': "fail", 'msg': "客户未登录"})
        exist_records = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id),
                                                    fav_type=int(fav_type))
        if exist_records:
            exist_records.delete()
            if int(fav_type) == 1:
                course = Course.objects.get(id=int(fav_id))
                course.fav_nums -= 1
                course.save()
            elif int(fav_type) == 2:
                course_org = CourseOrg.objects.get(id=int(fav_id))
                course_org.fav_nums -= 1
                course_org.save()
            elif int(fav_type) == 3:
                teacher = Teacher.objects.get(id=int(fav_id))
                teacher.fav_nums -= 1
                teacher.save()

            return JsonResponse({'status': "success", 'msg': "收藏"})
        else:
            if int(fav_id) > 0 and int(fav_type) > 0:
                UserFavorite.objects.create(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))
                if int(fav_type) == 1:
                    course = Course.objects.get(id=int(fav_id))
                    course.fav_nums += 1
                    course.save()
                elif int(fav_type) == 2:
                    course_org = CourseOrg.objects.get(id=int(fav_id))
                    course_org.fav_nums += 1
                    course_org.save()
                elif int(fav_type) == 3:
                    teacher = Teacher.objects.get(id=int(fav_id))
                    teacher.fav_nums += 1
                    teacher.save()
                return JsonResponse({'status': "success", 'msg': "已收藏"})
            else:
                return JsonResponse({'status': "fail", 'msg': "收藏出错"})


class TeacherListView(View):
    def get(self, request):
        all_teacher = Teacher.objects.all()

        sorted_teacher = all_teacher.order_by('-click_nums')[:2]

        # 搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_teacher = all_teacher.filter(Q(name__icontains=search_keywords))

        all_teacher_nums = all_teacher.count()

        # 排行
        try:
            sort = request.GET.get('sort', '')
        except Exception:
            sort = None
        if sort == 'hot':
            all_teacher = all_teacher.order_by('-click_nums')

        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        # Provide Paginator with the request object for complete querystring generation
        p = Paginator(all_teacher, request=request, per_page=1)

        all_teacher = p.page(page)

        return render(request, 'teachers-list.html', {
            "all_teacher": all_teacher,
            "all_teacher_nums": all_teacher_nums,
            "sort": sort,
            "sorted_teacher": sorted_teacher
        })


class TeacherDetailView(View):
    def get(self, request, teacher_id):
        teacher = Teacher.objects.filter(id=teacher_id).first()
        teacher.click_nums += 1
        teacher.save()
        all_courses = teacher.course_set.all()
        all_teacher = Teacher.objects.all()
        has_teacher_faved = False
        if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id=teacher.id):
            has_teacher_faved = True
        has_org_faved = False
        if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):
            has_org_faved = True

        sorted_teacher = all_teacher.order_by('-click_nums')[:2]
        return render(request, 'teacher-detail.html', {
            "teacher": teacher,
            "all_courses": all_courses,
            "sorted_teacher": sorted_teacher,
            'has_teacher_faved': has_teacher_faved,
            "has_org_faved": has_org_faved
        })
